#include "common.h"
#include <sys/ipc.h>
#include <sys/shm.h>
#include <semaphore.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>

#define SIZE 10

//int global_num;

typedef struct _product
{
	int flag;
	int num;
}product_t;

int main()
{
	int shmid;
	key_t key;
	product_t *shmaddr = NULL;

	key = ftok("./", 19);
	if(key < 0)
		err_sys("ftok error\n");

	shmid = shmget(key, SIZE, IPC_CREAT | 0666);
	if(shmid < 0)
		err_sys("shmget error\n");

	shmaddr = shmat(shmid, NULL, 0);
	printf("shmaddr : %p\n", shmaddr);
	if(shmaddr < 0)
		err_sys("shmat error\n");

	shmaddr->flag = 0;
	sem_t *sem = sem_open("tmp_sem", O_CREAT, 0666, 1);
	//sem_wait(sem);
	if((shmaddr->num < 10) || (shmaddr->flag == 0) || (shmaddr->flag == -1))
	{
		printf("Please input num.\n");
		sem_wait(sem);
		scanf("%d", &(shmaddr->num));
		
		if(shmaddr->num == 10)
		{
			printf("Warehouse is full.\n");
			shmaddr->flag = 2;
		}
		else if(shmaddr->num < 10)
		{
			printf("Add %d products.\n", shmaddr->num);
			shmaddr->flag = 1;
		}

		while(shmaddr->num > 10)
		{
			printf("Input error, please input num < 10\n");
			scanf("%d", &(shmaddr->num));
		}

	}
	else if(shmaddr->flag == 1)
	{
		printf("Customer is shopping.\n");
	}
	
	else
	{
		printf("Warehouse is full\n");
		sem_post(sem);
		sem_close(sem);
		shmaddr->flag = 2;
	}
	sem_post(sem);
	sem_close(sem);

	return 0;
}

